package com.wdl.fmnew.app.demo;

import com.wdl.fmnew.core.mvp.rxlife.RxLifeEvent;
import com.wdl.fmnew.core.mvp.rxlife.impl.BaseRxLifeModel;
import com.wdl.fmnew.core.net.api.ApiService;
import com.wdl.fmnew.core.net.callback.ApiListener;
import com.wdl.fmnew.core.net.utils.NetUtils;


import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wdl on 2017/9/18.
 */

public class DemoModel extends BaseRxLifeModel implements DemoContract.Model {
    @Inject
    ApiService apiService;

    @Inject
    public DemoModel() {
    }


    @Override
    public void getData(ApiListener<String> listener) {
        NetUtils.httpRequest(getComposeObservable(apiService.getCustmList(0, 0), RxLifeEvent.DESTROY), String.class, listener);
    }

    @Override
    public void mn() {
        Observable<String> compose = Observable.create(new ObservableOnSubscribe<String>() {

            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception {
                try {
                    Thread.sleep(5000);
                    // 这里可以处理更多操作,捕获到异常对 onError 进行处理
                    emitter.onNext("this is next");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    emitter.onError(e);
                }
            }
        });


        getComposeObservable(compose, RxLifeEvent.DESTROY)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        System.out.println("receive context:" + s);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 释放资源，解决rxjava内存泄露
     */
    @Override
    public void release() {
        onDestory();
    }
}
